//
//  WYTDiaryInfoSelectionVC.m
//  Diary
//
//  Created by lanou3g on 15/11/3.
//  Copyright © 2015年 王艺拓. All rights reserved.
//

#import "WYTDiaryInfoSelectionVC.h"
#import "WYTDiaryInfoSelectionView.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

#define kbaseImageViewWidth kScreenWidth * 0.85
#define kbaseImageViewHeight kbaseImageViewWidth * 1.618
#define kbaseImageViewMinY kScreenHeight * 0.26

@interface WYTDiaryInfoSelectionVC ()<CLLocationManagerDelegate, MKMapViewDelegate>

@property (nonatomic, strong)CLLocationManager *locationManager; // 定位
@property (nonatomic, strong)MKMapView *mapView; // 地图
@property (nonatomic, assign)CGFloat latitude;
@property (nonatomic, assign)CGFloat longitude;
@property (nonatomic, assign)MKCoordinateRegion region;
@property (nonatomic, assign)int mapLoadCount;


@property (nonatomic, strong)WYTDiaryInfoSelectionView *rootView;
@property (nonatomic, strong)UIImageView *fakeBGImageView;




@end

@implementation WYTDiaryInfoSelectionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpRootView];
    //骗一个过渡:加一个延迟触发,因为这里的View的背景是透明的,我在rootview底下加一个欺骗的图片
    //[self performSelector:@selector(addFakeBG) withObject:self afterDelay:0.3];
    [self addFakeBG];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.rootView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
    
    UISwipeGestureRecognizer *swipeDownToDismiss = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeDownToDismiss:)];
    swipeDownToDismiss.direction = UISwipeGestureRecognizerDirectionDown;
    
    
    [self.rootView addGestureRecognizer:swipeDownToDismiss];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [UIView animateWithDuration:0.3 animations:^{
        self.fakeBGImageView.alpha = 0;
    }];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    [UIView animateWithDuration:1 animations:^{
        self.rootView.clockImageView.alpha = 0;

        [UIView animateWithDuration:1 animations:^{
            self.rootView.clockImageView.alpha = 1;
        }];
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.rootView.baseImageView.frame = CGRectMake((kScreenWidth - kbaseImageViewWidth) / 2,  kScreenHeight * 0.035 + (kScreenHeight * 0.838 - kbaseImageViewHeight) , kbaseImageViewWidth, kbaseImageViewHeight);
    }];// (kScreenHeight - kbaseImageViewHeight) / 2
}

- (void)setUpRootView{
    self.rootView = [[WYTDiaryInfoSelectionView alloc]init];
    self.rootView.frame = CGRectMake(0, 736, kScreenWidth, kScreenHeight);
    self.view = self.rootView;
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAppearMap:)];
    [self.rootView.locationIconImageView addGestureRecognizer:tap];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tapToJumpOutDiaryInfoView:) name:@"TAPTOJUMPOUTDIARYINFOVIEW" object:nil];
}

- (void)tapToJumpOutDiaryInfoView:(NSNotificationCenter *)sender{
    //NSLog(@"我在新的VC里,让我下去把");
    [self.delegate modelTransmiting:self.rootView.diaryInfoModel];
     //NSLog(@"x === %f, y === %f, width === %f, height === %f", self.rootView.baseImageView.frame.origin.x, self.rootView.baseImageView.frame.origin.y, self.rootView.baseImageView.frame.size.width, self.rootView.baseImageView.frame.size.height);
//    [UIView animateWithDuration:0.3 animations:^{
//       
//        //self.rootView.baseImageView.frame = CGRectMake(31.05, 736, 351.9, 568.374);
//    }];
    
    [self performSelector:@selector(delayToDismissAfterAnimation) withObject:self afterDelay:0.3];
}

- (void)delayToDismissAfterAnimation{
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

- (void)addFakeBG{
    self.fakeBGImageView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.fakeBGImageView.image = self.backgroundImageForFakeImage;
    [self.rootView addSubview:self.fakeBGImageView];
    
//    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//    UIVisualEffectView *blurView = [[UIVisualEffectView alloc]initWithEffect:effect];
//    blurView.frame = [UIScreen mainScreen].bounds;
//    //[fakeBGImageView addSubview:blurView];
    [self.rootView sendSubviewToBack:self.fakeBGImageView];
}

- (void)swipeDownToDismiss:(UISwipeGestureRecognizer *)sender{
    [self.delegate modelTransmiting:self.rootView.diaryInfoModel];
    
    [UIView animateWithDuration:0.3 animations:^{
        //self.rootView.frame = CGRectMake(0, 736, kScreenWidth, kScreenHeight);
    }];
    
    [self performSelector:@selector(delayToDismissAfterAnimation) withObject:self afterDelay:0.3];
}


- (void)tapAppearMap:(UITapGestureRecognizer *)sender{
    
#warning 1111111111111111111111
    NSLog(@"1gdxk;ldkfsakjdflksjdlfkjkkkkkkkkkkkkkkkkkdf");
    if (self.mapLoadCount == 0) {
        [self appearMap];
        self.mapLoadCount++;
    }
    [self.locationManager stopUpdatingLocation];
    self.rootView.emptyLocationImageView.alpha = 0;
    if ([self.rootView.locationTextView.text isEqualToString:@""]) {
        self.rootView.locationTextView.userInteractionEnabled = NO;
        [self.locationManager startUpdatingLocation];
        //NSLog(@"1");
    } else {
        //NSLog(@"2");
        [self.locationManager stopUpdatingLocation];
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:self.rootView.locationTextView.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark *placemark = [placemarks firstObject];
            
            MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
            point.coordinate = placemark.location.coordinate;
            [self.mapView removeAnnotations:self.mapView.annotations];
            [self.mapView addAnnotation:point];
            [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude) animated:YES];
            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude), 2000, 2000);
            [self.mapView setRegion:region];
        }];
    }
}

#pragma mark == 地图
- (void)appearMap{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    // 定位的精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 多少米更新一次
    self.locationManager.distanceFilter = 100;
    // 什么时候请求位置
    [self.locationManager requestAlwaysAuthorization];
    
    
    // 地图
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.rootView.mapBaseView.frame), CGRectGetHeight(self.rootView.mapBaseView.frame))];
    self.mapView.delegate = self;
    self.mapView.layer.cornerRadius = 0.0187*kScreenWidth;
    // 设置地图跟随位置移动
//    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    // 设置地图样式
    self.mapView.mapType = MKMapTypeStandard;
//    self.mapView.showsUserLocation = YES;
    // 比例尺
    [self.mapView setZoomEnabled:YES];
    self.mapView.showsScale = YES;
    [self.rootView.mapBaseView addSubview:self.mapView];
    
}
#pragma mark ==== location代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //NSLog(@"定位成功");
    CLLocation *location = [locations lastObject];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [self.mapView setCenterCoordinate:location.coordinate animated:YES];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = [placemarks firstObject];
        self.rootView.locationTextView.text = placemark.name;
        //NSLog(@"%@", placemark.name);
        self.latitude = placemark.location.coordinate.latitude;
        self.longitude = placemark.location.coordinate.longitude;
        MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
        point.coordinate = placemark.location.coordinate;
        [self.mapView removeAnnotations:self.mapView.annotations];
        [self.mapView addAnnotation:point];
//        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude) animated:YES];
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(placemark.location.coordinate.latitude, placemark.location.coordinate.longitude), 2000, 2000);
        [self.mapView setRegion:region];
        self.rootView.locationTextView.userInteractionEnabled = YES;
    }];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    self.rootView.locationTextView.userInteractionEnabled = YES;
    if ([error code] == kCLErrorDenied) {
        //NSLog(@"访问被拒绝");
    } else {
        //NSLog(@"---%@", error);
        //NSLog(@"无法获取位置信息");
    }
}

#pragma mark ===== mapView代理方法
- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView{
    //NSLog(@"当需要从Google服务器取得新地图时");
}
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{
    //NSLog(@"当成功地取得地图后");
}
- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error{
    //NSLog(@"娶得地图失败后");
}
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    //NSLog(@"当手势开始（拖拽，放大，缩小，双击)");
}
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    //NSLog(@"当手势结束（拖拽，放大，缩小，双击)");
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
